package cn.deschen.eshop.common.api;

import cn.deschen.eshop.common.enums.GlobalEnum;
import cn.deschen.eshop.common.enums.IEnum;

import java.util.Map;

/**
 * @Author hanbin_chen
 * @Description 通用结果集，使用泛型替代object，避免强制转换而自动隐式转换，提高代码重用率
 * @DateTime 2021/1/12
 * @Version 1.0.0
 */
public class CommonRes<T> {

    public final static String MSG_TEMPLATE = "%s : %s";

    /**
     * 错误码.
     */
    private Integer code;

    /**
     * 提示信息.
     */
    private String message;

    /**
     * 返回成功的数据
     */
    private T data;

    protected CommonRes(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> CommonRes<T> success(T data) {
        return new CommonRes<T>(GlobalEnum.SUCCESS.getCode(), GlobalEnum.SUCCESS.getMessage(), data);
    }

    public static <T> CommonRes<T> success() {
        return success(null);
    }

    public static <T> CommonRes<T> failure(Integer code, String message, T data) {
        return new CommonRes<T>(code, message, data);
    }

    public static <T> CommonRes<T> failure(Integer code, String message) {
        return new CommonRes<T>(code, message, null);
    }

    public static <T> CommonRes<T> failure(IEnum iEnum, String message) {
        return failure(iEnum.getCode(),
                String.format(MSG_TEMPLATE, iEnum.getMessage(), message));
    }

    public static <T> CommonRes<T> failure(IEnum iEnum) {
        return failure(iEnum.getCode(), iEnum.getMessage());
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

}
